package work.managercenter;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.zip.GZIPInputStream;

public class VRPFeedUnzip {

	private static final String dbClass = "com.mysql.jdbc.Driver";

	public static void main(String[] args) {
		//
		//		String dbUrl = "jdbc:mysql://192.168.1.199:3306/websimpl_aptrate";
		//		String user = "aptratings";
		//		String password = "password";

		// Staging
				String dbUrl = "jdbc:mysql://172.16.12.27:3306/websimpl_aptrate";
				String user = "usraptratings";
				String password = "F1ndm3@g00dAPT$";

		// PROD
//		String dbUrl = "jdbc:mysql://10.16.128.83:3306/websimpl_aptrate";
//		String user = "aptratings";
//		String password = "password";

		int[] feedIds = new int[]{       189004,
			       189002,
			       189003,
			       189001,
			       189000,
			       188999,
			       188998,
			       188997,
			       188996,
			       188995 };

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			Class.forName(dbClass);
			conn = DriverManager.getConnection(dbUrl, user,password);

			ps = conn.prepareStatement("select xml_data from partner_feed_data where feed_data_id = ?");

			for (int i = 0; i < feedIds.length; i++) {
				int n = feedIds[i];
				System.out.println(n);

				ps.setInt(1, n);
				ps.execute();
				rs = ps.getResultSet();

				while (rs.next()) {
					Blob blob = rs.getBlob("xml_data");

					FileWriter fw = null;
					try {
						fw = new FileWriter("/home/gmarcone/Carpeta sin título/" + n + ".xml");
						ungzipReview(blob.getBinaryStream(), fw);
					} catch (IOException e) {
						e.printStackTrace(System.out);
					} finally {
						if (fw != null) {
							fw.flush();
							fw.close();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace(System.out);
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace(System.out);
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace(System.out);
				}
			}
		}
	}

	public static void ungzipReview(InputStream input, FileWriter fw) {
		try {
			GZIPInputStream zip = new GZIPInputStream(input);
			utils.MyUtils.copy(zip, fw);
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
	}

}
